// import store from '../store'
// import { getDetail } from "@/apiOptions/home_api.js";

Function.prototype.method = function (name, fn) {
    this.prototype[name] = fn;
    return this;
  }
  
  if (!String.prototype.trim) {
    String.method("trim", function () {
      return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
    })
  }
  var isType = function (type) {
    return function (obj) {
      return Object.prototype.toString.call(obj) == '[object ' + type + ']';
    };
  };
  var isArray = isType("Array");
  var isStr = isType("String");
  var isObject = isType("Object");
  var isFun = isType("Function");
  var isRegExp = isType("RegExp");
  const TOOL = {
    isArray: isArray,
    isStr: isStr,
    isObject: isObject,
    isFun: isFun,
    isRegExp: isRegExp,
    extend: function () {
      var options, copyIsArray,
        target = arguments[0] || {},
        i = 1,
        length = arguments.length,
        deep = false;
  
      if (typeof target === "boolean") {
        deep = target;
        target = arguments[i] || {};
        i++;
      }
      if (i === length) {
        target = this;
        i--;
      }
      for (; i < length; i++) {
        if ((options = arguments[i]) != null) {
          for (let name in options) {
            let clone,
              src = target[name],
              copy = options[name];
            if (target === copy) continue;
            if (deep && copy && (isObject(copy) ||
                (copyIsArray = isArray(copy)))) {
              if (copyIsArray) {
                copyIsArray = false;
                clone = src && isArray(src) ? src : [];
              } else {
                clone = src && isObject(src) ? src : {};
              }
              target[name] = this.extend(deep, clone, copy);
            } else if (copy !== undefined) {
              target[name] = copy;
            }
          }
        }
      }
      return target;
    },
  
    // openLoading() {
    //   store.dispatch('saveIsLoading', true)
    // },
    // closeLoading() {
    //   store.dispatch('saveIsLoading', false)
    // },
  
    getStorage(item) {
      var value = window.localStorage.getItem(item)
      if (value) {
        value = this.decrypt(value);
        if (value.indexOf("time") > -1) value = JSON.parse(value)
        if (value.time && value.expires) { //设置了过期时间
          let newTime = new Date().valueOf(),
            oldTime = value.time;
          if (newTime - oldTime > value.expires) {
            window.localStorage.removeItem(item);
            value = ""
          } else {
            value = value.value ? value.value : value
          }
        }
      }
      return value;
    },
    setStorage(obj) {
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          window.localStorage.setItem(key, this.encrypt(String(obj[key])));
        }
      }
    },
    clearStorage(mess) {
      if (mess) {
        mess.forEach(item=>{
          window.localStorage.removeItem(item)
        })
      } else {
        window.localStorage.clear();
      }
    },
    getSession(item) {
      var value;
      value = window.sessionStorage.getItem(item)
      return (value ? this.decrypt(value) : '')
    },
    setSession(obj) {
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          window.sessionStorage.setItem(key, this.encrypt(String(obj[key])));
        }
      }
    },
    clearSession() {
      function clearCookie() {
        var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
        if (keys) {
          for (var i = keys.length; i--;)
            document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
        }
      }
  
      if (window.sessionStorage) {
        window.sessionStorage.clear();
      } else {
        clearCookie();
      }
      // return this;
    },
    encrypt(value) {
      var encryptValue = ''
      var mask
      var maskValue
      for (var i = 0, len = value.length; i < len; i++) {
        mask = Math.round(Math.random() * 111) + 77
        maskValue = value.charCodeAt(i) + mask
        mask += i
        encryptValue += String.fromCharCode(maskValue, mask)
      }
      return encryptValue
    },
    decrypt(value) {
      var decryptValue = ''
      var k = 0
      var v
      var m
      var decrypt = function (v, m, i) {
        v = v.charCodeAt(0)
        m = m.charCodeAt(0)
        m -= i
        v -= m
        return String.fromCharCode(v)
      }
      for (var i = 0, len = value.length; i < len; i++) {
        if (!(i % 2)) {
          v = value[i]
        } else {
          m = value[i]
          decryptValue += decrypt(v, m, k)
          k++
        }
      }
      return decryptValue
    },
    getToken() {
      return this.getStorage("X-Token") || ''
    },
    getCookie: function (name) {
      var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
      if (arr = document.cookie.match(reg))
        return unescape(arr[2]);
      else
        return null;
    },
    setCookie: function (name, value, day) {
      if (day !== 0) { //当设置的时间等于0时，不设置expires属性，cookie在浏览器关闭后删除
        var expires = day * 24 * 60 * 60 * 1000;
        var date = new Date(+new Date() + expires);
        document.cookie = name + "=" + escape(value) + ";expires=" + date.toUTCString();
      } else {
        document.cookie = name + "=" + escape(value);
      }
    },
    delCookie: function (name) {
      this.setCookie(name, ' ', -1);
    },
    copy: function (source) {
      let result = Array.isArray(source) ? [] : {};
      for (var key in source) {
        result[key] = source[key] != null && typeof source[key] === 'object' ? this.copy(source[key]) : source[key];
      }
      return result;
    },
    getTime: function (t) {
      if (!t) return new Date().getTime();
      return new Date(String(t).replace(/-/g, "/")).getTime();
    },
    dateFtt: function (fmt, date) {
      if (typeof date === "string" || typeof date === "number") {
        date.indexOf("-")>-1 && (date = date.replace(/\-/g,'/'));
        date = new Date(date);
      }
      var o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "h+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
      };
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
      for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      return fmt;
    },
  
    getUrlParams(name) {
      var url = '';
      if (window.location.search == '') {
        url = window.location.hash;
      } else {
        url = window.location.search;
      }
  
      // var url = window.location.search;
      // var url = window.location.hash;
      var n = url.indexOf('?');
      // if (url.indexOf('?') == 1) {
      //   return false;
      // }
      url = url.substr(n + 1);
      url = url.split('&');
      var name = name || '';
      var nameres;
      for (var i = 0; i < url.length; i++) {
        var info = url[i].split('=');
        var obj = {};
        obj[info[0]] = decodeURI(info[1]);
        url[i] = obj;
      }
      if (name) {
        for (var i = 0; i < url.length; i++) {
          for (const key in url[i]) {
            if (key == name) {
              nameres = url[i][key];
            }
          }
        }
      } else {
        nameres = url;
      }
      return nameres;
    },
  
  
    //数组对象深拷贝
    deepClone: function (obj) {
      let objClone = Array.isArray(obj) ? [] : {};
      if (obj && typeof obj === "object") {
        for (let key in obj) {
          if (obj.hasOwnProperty(key)) {
            //判断ojb子元素是否为对象，如果是，递归复制
            if (obj[key] && typeof obj[key] === "object") {
              objClone[key] = this.deepClone(obj[key]);
            } else {
              //如果不是，简单复制
              objClone[key] = obj[key];
            }
          }
        }
      }
      return objClone;
    },
    //手机号隐藏四位
    repPhoneNum(val){
      if(val){
        return val.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
      } else{
        return '-'
      }
    },
  
    // EXLCL
  isExcel(type,name, data) {
    const link = document.createElement('a')
    const blob = new Blob([data])
    link.style.display = 'none'
    link.href = URL.createObjectURL(blob)
    link.setAttribute('download', `${name}.`+type)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  },
  

  getTimeRi(n) {
    //本周、上周
    var now = new Date();
    var year = now.getFullYear();
    //因为月份是从0开始的,所以获取这个月的月份数要加1才行
    var month = now.getMonth() + 1;
    var date = now.getDate(); //日期
    var day = now.getDay(); //星期
    // console.log(date);
    //判断是否为周日,如果不是的话,就让今天的day-1(例如星期二就是2-1)
    if (day !== 0) {
      n = n + (day - 1);
    } else {
      n = n + day;
    }
    if (day) {
      //这个判断是为了解决跨年的问题
      if (month > 1) {
        month = month;
      }
      //这个判断是为了解决跨年的问题,月份是从0开始的
      else {
        year = year - 1;
        month = 12;
      }
    }
    now.setDate(now.getDate() - n);

    year = now.getFullYear();
    month = now.getMonth() + 1;
    date = now.getDate();
    // console.log(n);
    let s =
      year +
      "-" +
      (month < 10 ? "0" + month : month) +
      "-" +
      (date < 10 ? "0" + date : date);
    return s;
  },

  getDayRi(day) {
    var today = new Date();
    var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
    today.setTime(targetday_milliseconds); //注意，这行是关键代码
    var tYear = today.getFullYear();
    var tMonth = today.getMonth() + 1;
    var tDate = today.getDate();
    tMonth = tMonth < 10 ? "0" + tMonth : tMonth;
    tDate = tDate < 10 ? "0" + tDate : tDate;
    return tYear + "-" + tMonth + "-" + tDate;
  },

  getMonthStartAndEnd(AddMonthCount) {
    //起止日期数组
    var startStop = new Array();
    //获取当前时间
    var currentDate = new Date();
    var month = currentDate.getMonth() + AddMonthCount;
    if (month < 0) {
      var n = parseInt(-month / 12);
      month += n * 12;
      currentDate.setFullYear(currentDate.getFullYear() - n);
    }
    currentDate = new Date(currentDate.setMonth(month));
    //获得当前月份0-11
    var currentMonth = currentDate.getMonth();
    //获得当前年份4位年
    var currentYear = currentDate.getFullYear();
    //获得上一个月的第一天
    var currentMonthFirstDay = new Date(currentYear, currentMonth, 1);
    //获得上一月的最后一天
    var currentMonthLastDay = new Date(currentYear, currentMonth + 1, 0);
    //添加至数组
    startStop.push(this.formatDate(currentMonthFirstDay));
    startStop.push(this.formatDate(currentMonthLastDay));
    //返回
    return startStop;
  },
  formatDate(date) {
    var year = "";
    var month = "";
    var day = "";
    var now = date;
    year = "" + now.getFullYear();
    if (now.getMonth() + 1 < 10) {
      month = "0" + (now.getMonth() + 1);
    } else {
      month = "" + (now.getMonth() + 1);
    }
    if (now.getDate() < 10) {
      day = "0" + now.getDate();
    } else {
      day = "" + now.getDate();
    }
    return year + "-" + month + "-" + day;
  },
  
  
  timeSub(time) {
    return time.substring(0, time.length - 3);
  },
  
    
  
  }
  export default TOOL;
  
  //手机号隐藏中间4位
  
  // export const WB = new wb(["router", "progress"]);